package com.huluobo.a2203parkdemo.patrol

import android.app.AlertDialog
import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.content.DialogInterface
import android.content.DialogInterface.OnClickListener
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.EditText
import android.widget.TimePicker
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2203parkdemo.R
import com.huluobo.a2203parkdemo.adapter.PointAdapter
import com.huluobo.a2203parkdemo.databinding.ActivityAddPatrolBinding
import com.huluobo.base.bean.PPointItem
import com.huluobo.base.bean.PPointItemList
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.StringBuilder
import java.util.Calendar

@AndroidEntryPoint
class AddPatrolActivity : BaseActivity<ActivityAddPatrolBinding, PatrolViewModel>() {
    private lateinit var pointAdapter: PointAdapter
    private val pointList = mutableListOf<PPointItem>()
    private val newPointList = mutableListOf<PPointItem>()

    private var pEnd = ""
    private var pPoint = ""
    private var pStart = ""
    private var pTime = ""
    override fun initData() {
        viewModel.getAllPoint()

        viewModel.getAllPointSuccess.observe(this) {
            val pointList = Gson().fromJson(it, PPointItemList::class.java)
            pointAdapter.data.clear()
            pointAdapter.data.addAll(pointList)
            pointAdapter.notifyDataSetChanged()
            this.pointList.addAll(pointList)
        }

        viewModel.addPointSuccess.observe(this) {
            ToastUtils.showLong("添加成功")
            viewModel.getAllPoint()
        }

        viewModel.addPatrolSuccess.observe(this) {
            ToastUtils.showLong("添加成功")
            finish()
        }
    }

    var time1 = 0L
    var time2 = 0L
    var time = 0L

    val calendar = Calendar.getInstance().apply {
        //声明一个时间,把时间归为0点,这样赋值的时候就是从0点开始
        set(Calendar.HOUR_OF_DAY, 0)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }


    override fun initView() {
        binding.addPatrolPointRv.layoutManager = GridLayoutManager(this, 2)
        pointAdapter = PointAdapter()
        binding.addPatrolPointRv.adapter = pointAdapter

        val pointListLiveData = MutableLiveData<List<PPointItem>>()
        pointAdapter.setOnItemClickListener { adapter, view, position ->
            val pPointItem = PPointItem(pointList[position].pointId, pointList[position].pointName)
            newPointList.add(pPointItem)
            pointListLiveData.postValue(newPointList)
        }

        pointListLiveData.observe(this) {
            pPoint = ""
            val points = StringBuilder()
            newPointList.forEach {
                points.append(it.pointName)
                points.append(",")
            }
            binding.addPatrolChoicePointTv.text = points.toString()
            pPoint = Gson().toJson(it)
        }
        binding.addPatrolStartTimeBtn.setOnClickListener {
            val calendar = Calendar.getInstance()
            TimePickerDialog(this, object : OnTimeSetListener {
                override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
                    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                    calendar.set(Calendar.MINUTE, minute)
                    time1 = calendar.timeInMillis
                    binding.addPatrolStartTimeNowTv.text = "$hourOfDay:$minute"
                    pStart = "$hourOfDay:$minute"
                }
            }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true).show()
        }

        binding.addPatrolEndTimeBtn.setOnClickListener {
            val calendar = Calendar.getInstance()
            TimePickerDialog(this, object : OnTimeSetListener {
                override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
                    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                    calendar.set(Calendar.MINUTE, minute)
                    binding.addPatrolEndTimeNowTv.text = "$hourOfDay:$minute"
                    pEnd = "$hourOfDay:$minute"
                    time2 = calendar.timeInMillis
                    time = time2 - time1
                    if (time <= 0) {
                        ToastUtils.showLong("请重新选择时间")
                    } else {
                        val newTime = (time / 1000 / 60 / 60).toFloat()
                        binding.addPatrolTimeTv.text = "${newTime}小时"
                        pTime = "${newTime}小时"
                    }
                }
            }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true).show()
        }

        binding.addPatrolAddPointBtn.setOnClickListener {
            val dialogView = layoutInflater.inflate(R.layout.dialog_add_point, null)
            AlertDialog.Builder(this)
                .setView(dialogView)
                .setTitle("添加巡逻点")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定") { dialog, which ->
                    //上传添加巡逻点的接口
                    val editText = dialogView.findViewById<EditText>(R.id.dialog_add_point_ed)
                    val map = mutableMapOf<String, String>()
                    if (!editText.text.isNullOrEmpty()) {
                        map[Const.PARAM_POINT_NAME] = editText.text.toString()
                        val json = Gson().toJson(map)
                        val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                        viewModel.addPoint(body)
                    } else {
                        editText.error = "巡逻点不能为空"
                    }
                }
                .show()
        }
//        {
//            "pEnd": "string",
//            "pPoint": "string",
//            "pStart": "string",
//            "pTime": "string",
//        }
        binding.addPatrolCommitBtn.setOnClickListener {
            if (pEnd.isNotEmpty() && pPoint.isNotEmpty() && pStart.isNotEmpty() && pTime.isNotEmpty()) {
                val map = mutableMapOf<String, String>()
                map[Const.PARAM_P_END] = pEnd
                map[Const.PARAM_P_POINT] = pPoint
                map[Const.PARAM_P_START] = pStart
                map[Const.PARAM_P_TIME] = pTime

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                viewModel.addPatrol(body)

            } else {
                ToastUtils.showLong("不能有空选项")
            }
        }
    }
}